#include "myLogger.h"

//定义静态成员变量
QMutex MyLogger::m_logMutex;

QList<QtMsgType> MyLogger::m_levelList;

QString MyLogger::m_logFile;

void MyLogger::debug(QString msg) {
	qDebug() << QString::fromUtf8(msg.toUtf8());
}

void MyLogger::info(QString msg) {
	qInfo() << QString::fromUtf8(msg.toUtf8());
}

void MyLogger::warning(QString msg) {
	qWarning() << QString::fromUtf8(msg.toUtf8());
}

void MyLogger::error(QString msg) {
	qCritical() << QString::fromUtf8(msg.toUtf8());
}

void MyLogger::initLog(QString logLevel, QString filename) {
	if (logLevel.isEmpty()) {
		qSetMessagePattern("%{type} [%{time yyyy-MM-dd hh:mm:ss.zzz}] %{function}(%{line}): %{message}");
	} else {
		//在release模式下输出日志到文件
		QtMsgType type = QtDebugMsg;
		QString level = logLevel.toUpper();
		if (level == "DEBUG") {
			m_levelList = { QtDebugMsg, QtInfoMsg, QtWarningMsg ,QtCriticalMsg, QtFatalMsg };
		} else if (level == "INFO") {
			m_levelList = { QtInfoMsg, QtWarningMsg ,QtCriticalMsg, QtFatalMsg };
		} else if (level == "WARNING") {
			m_levelList = { QtWarningMsg ,QtCriticalMsg, QtFatalMsg };
		} else if (level == "ERROR") {
			m_levelList = { QtCriticalMsg, QtFatalMsg };
		}
		if (!filename.isEmpty()) {
			m_logFile = filename;
		} else {
			m_logFile = "./log";
		}
		m_logFile = QString("%1/%2.log").arg(filename).arg(QDateTime::currentDateTime().toString("yyyy_MM_dd"));
		qInstallMessageHandler(MyLogger::customMessageHandler);
	}
}

MyLogger::MyLogger() {}

MyLogger::~MyLogger() {}

void MyLogger::customMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString& msg) {
	//为了线程安全
	m_logMutex.lock();
	//设置输出日志级别，小于该级别，将不会写入日志文件，默认是warning级别，即debug信息不会写入日志文件
	if (m_levelList.contains(type)) {
		//日志级别
		QString category;
		//日志信息
		switch (type) {
			case QtDebugMsg:
				category = "DEBUG";
				break;
			case QtWarningMsg:
				category = "WARNING";
				break;
			case QtCriticalMsg:
				category = "ERROR";
				break;
			case QtInfoMsg:
				category = "INFO";
				break;
			case QtFatalMsg:
				category = "FATAL";
				abort();
		}
		//拼接日志信息
		QString logInfo = QString("%1 [%2] %3(%4): %5")
			.arg(category, 7, ' ')
			.arg(QDateTime::currentDateTime().toString("yyyy/MM/dd hh:mm:ss"))
			.arg(context.function)
			.arg(context.line)
			.arg(msg);

		//在RELEASE模式下输出数据到文件
		QFile outFile(m_logFile);
		outFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text);
		QTextStream ts(&outFile);
		ts << logInfo << Qt::endl;
		outFile.close();
	}
	m_logMutex.unlock();
}
